package peer.dstdb.message;

import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;

import peer.Message;
import peer.dstdb.DBConfig;
import peer.dstdb.SourceGroup;
import peer.p2pnet.SourceNode;
import peer.p2pnet.SourceNodeIdent;
import peer.tools.ByteShortSwitch;
import peer.tools.Mdb;


public class SourceSearchMessage2 extends Message{
	public short sType=peer.tools.MessageType.sType_DB_SourceSearchMessage2;
	byte[] dpData=null;
	byte[] sourceByte;
	HashMap<SourceNodeIdent, SourceNode> sourceNodeMember;
	Mdb mdb;
	short blockNum;
	short sourceSum;
	public SourceSearchMessage2(Mdb mdb,short blockNum,InetAddress gIp){
		this.mdb=mdb;
		this.blockNum=blockNum;
		SourceGroup sg=DBConfig.sourceGroupMange.getSourceGroup(mdb);
		sourceByte=sg.getSourceGroupByte(blockNum,gIp);
		dpData=new byte[24+sourceByte.length];
		ByteShortSwitch.toByteArray(ver, dpData, 0);  //add: ver
		ByteShortSwitch.toByteArray(sType, dpData, 2);  //add: service type
		System.arraycopy(mdb.md, 0, dpData, 4, 16);
		ByteShortSwitch.toByteArray(blockNum, dpData, 20);
		
		System.arraycopy(sourceByte, 0, dpData, 22, sourceByte.length);
		dp=new DatagramPacket(dpData,dpData.length);
	}
	
	public SourceSearchMessage2(DatagramPacket dp){
		this.dp=dp;
		dpData=dp.getData();
		ver=ByteShortSwitch.toShort(dpData, 0);
		sType=ByteShortSwitch.toShort(dpData, 2);
		byte[] md=new byte[16];
		System.arraycopy(dpData, 4, md, 0, 16);
		mdb=new Mdb(md);
		blockNum=ByteShortSwitch.toShort(dpData, 20);
		
		sourceSum=ByteShortSwitch.toShort(dpData, 22);
		sourceNodeMember=new HashMap<SourceNodeIdent, SourceNode>(sourceSum);
		for(int i=0;i<sourceSum;i++){
			byte[] b1=new byte[4];
			System.arraycopy(dpData, 24+i*12, b1, 0, 4);
			InetAddress assistNodeIp=null;
			try {
				assistNodeIp=InetAddress.getByAddress(b1);
			} catch (UnknownHostException e) {
				e.printStackTrace();
			}
			int assistNodePort=peer.tools.ByteIntSwitch.toInt(dpData, 6+i*12+4+18);
			int assistSessionId=peer.tools.ByteIntSwitch.toInt(dpData, 6+i*12+8+18);
			SourceNodeIdent sni=new SourceNodeIdent(assistSessionId,assistNodeIp,assistNodePort);
			sourceNodeMember.put(sni, null);
		}
	}
	
	public HashMap<SourceNodeIdent, SourceNode> getSourceMember(){
		return sourceNodeMember;
	}
	
	public Mdb getMdb(){
		return mdb;
	}
	
	public short getBlockNum(){
		return blockNum;
	}
}



